package cn.com.hellowood.springsecurity.controller;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * The type Main controller.
 *
 * @author HelloWood
 */
@Controller
public class MainController {

    /**
     * Root page.
     *
     * @return the index page url
     */
    @RequestMapping("/")
    public String root() {
        return "redirect:/index";
    }

    /**
     * Index page.
     *
     * @return the index page url
     */
    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    /**
     * User index page.
     *
     * @return the user index page url
     */
    @RequestMapping("/user/index")
    public String userIndex() {
        return "user/index";
    }

    /**
     * Login page.
     *
     * @return the login page url
     */
    @RequestMapping("/login")
    public String login() {
        return "login";
    }





      /*
      http.authorizeRequests()
              .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/dba/**").hasAnyRole("ADMIN", "DBA")
            .and()
                .formLogin().loginPage("/login")
                .defaultSuccessUrl("/welcome").failureUrl("/login?error")
                .usernameParameter("user-name").passwordParameter("pwd")
            .and()
                .logout().logoutSuccessUrl("/login?logout")
            .and()
                .exceptionHandling().accessDeniedPage("/403")
            .and()
                .csrf();*/
    //获取session存储的SPRING_SECURITY_LAST_EXCEPTION的值，自定义错误信息
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView login(
            @RequestParam(value = "error", required = false) String error,
            @RequestParam(value = "logout", required = false) String logout,
            HttpServletRequest request) {
        ModelAndView model = new ModelAndView();

        model.addObject("name", SecurityContextHolder.getContext().getAuthentication().getName());

        if (error != null) {
            model.addObject("loginError", true);
            model.addObject("error", getErrorMessage(request, "SPRING_SECURITY_LAST_EXCEPTION"));
        }
        if (logout != null) {
            model.addObject("msg", "你已经成功退出");
        }
        model.setViewName("login");
        return model;
    }

    //自定义错误类型
    private String getErrorMessage(HttpServletRequest request, String key){
        Exception exception =
                (Exception) request.getSession().getAttribute(key);
        String error;
        if (exception instanceof BadCredentialsException) {
            error = "不正确的用户名或密码";
        }else if(exception instanceof LockedException) {
            error = exception.getMessage();
            error = "登录错误次数过多";
        }else{
            error = "不正确的用户名或密码";
        }
        return error;
    }



    /**
     * Login error page.
     *
     * @param model the model
     * @return the login error page url
     */
    @RequestMapping("/login-error")
    public String loginError(Model model) {
        model.addAttribute("loginError", true);
        return "login";
    }

}
